package sk.openit.xml.jaxp.dom;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import sk.openit.xml.entity.DbConfig;
import sk.openit.xml.entity.DbConfigTags;

public class DbConfigReader implements DbConfigTags {
	private Document doc;
	private String fileName;
	private DbConfig config;
	
	public DbConfigReader(String fileName) {
		this.fileName = fileName;
		this.config = new DbConfig();
	}

	public void process() {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(new File(fileName));
			doc.getDocumentElement().normalize();

			config.setDbType(doc.getDocumentElement().getAttribute(DB_TYPE));

			NodeList nList = doc.getElementsByTagName(CONFIG);

			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element eElement = (Element) nNode;

					config.setHost(getTagValue(HOST, eElement));
					config.setPort(getTagValue(PORT, eElement));
					config.setInstance(getTagValue(INSTANCE, eElement));
					config.setDatabase(getTagValue(DATABASE, eElement));
					config.setUser(getTagValue(USER, eElement));
					config.setPassword(getTagValue(PASSWORD, eElement));
				}
			}
		} catch (SAXException spe) {
			System.err.println("Unable to parse XML structure: " + fileName);
			spe.printStackTrace();
		} catch (ParserConfigurationException pce) {
			System.err.println("Wrong SAXParser configuration");
			pce.printStackTrace();
		} catch (IOException ioe) {
			System.err.println("Unable to open xml file: " + fileName);
			ioe.printStackTrace();
		}
	}

	private String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
		Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}

	public DbConfig getConfig() {
		return config;
	}	
}